package com.coolsummer.limiter;

import com.coolsummer.abstracts.Limiter;
import com.google.common.util.concurrent.RateLimiter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author coolsummer
 * @describe Guava限流
 * @date 2019/11/18 17:22
 */
public class GuavaLimiter extends Limiter{

    private static Map<String,RateLimiter> resourceLimiter = new ConcurrentHashMap<>();

    /**
     * 限流的资源
     */
    private String resource = "order";

    public GuavaLimiter(double qps) {
        super(qps);
        createResourceLimiter(resource,qps);
    }

    public void createResourceLimiter(String resource,double qps){
        if(resourceLimiter.containsKey(resource)){
            resourceLimiter.get(resource).setRate(qps);
        } else {
            RateLimiter rateLimiter = RateLimiter.create(qps);
            resourceLimiter.putIfAbsent(resource, rateLimiter);
        }
    }

    @Override
    public boolean tryAcquire(){
        return resourceLimiter.get(resource).tryAcquire();
    }
}
